package com.gxa.service.impl;

import com.gxa.common.R;
import com.gxa.mapper.PermissionMapper;
import com.gxa.pojo.Menu;
import com.gxa.pojo.Permission;
import com.gxa.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {


    @Autowired
    private PermissionMapper mapper;

    /**
     * 获取菜单列表
     * @param session
     * @return
     */
    @Override
    public R menuList(HttpSession session) {
        // 判断是否是超级管理员
        Boolean isSuper = (Boolean) session.getAttribute("isSuper");
        List<Permission> permissions = new ArrayList<>();
        if (isSuper) {
            // 超级管理员需要从数据库中拿数据
            permissions = mapper.findAll();
        }else {
            // 非超级管理员从session中获取数据
            permissions = (List<Permission>) session.getAttribute("permissions");
        }
        // 将 权限转换成菜单
        List<Menu> menus = getMenus(permissions);
        return new R(200, "success!", menus);
    }

    /**
     * 将权限转换成菜单
     * @param permissions
     */
    private List<Menu> getMenus(List<Permission> permissions){
        List<Menu> menus = new ArrayList<>();

        for (Permission permission : permissions) {
            // 判断是否是一级菜单
            if (permission.getParentId().equals(0) && permission.getPermissionLevel().equals(1) && permission.getIsMenu().equals(1)) {
                menus.add(new Menu(permission.getPermissionId(), permission.getPermissionName(), permission.getPermissionUrl(), permission.getParentId()));
            }
        }

        // 通过一级权限获取二级菜单
        for (Menu menu : menus) {
            List<Menu> subMenus = new ArrayList<>();
            for (Permission permission : permissions) {
                // 添加二级菜单？
                // menu的id == permission的父级id, 说明当前这个permission 就是一个子菜单
                if (permission.getParentId().equals(menu.getMenuId()) && permission.getPermissionLevel().equals(2) && permission.getIsMenu().equals(1)){
                    subMenus.add(new Menu(permission.getPermissionId(), permission.getPermissionName(), permission.getPermissionUrl(), permission.getParentId()));
                }
            }
            // 子菜单
            menu.setSubMenus(subMenus);
        }

        return menus;
    }
}
